package com.jiazhong.mingxing.boot.boot14.listener;

import com.alibaba.fastjson.JSONArray;
import com.jiazhong.mingxing.boot.boot14.bean.Order;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class Order2TransactionListener implements TransactionListener {
    @Override
    public LocalTransactionState executeLocalTransaction(Message message, Object o) {
        // 假设如果数量大于5，库存不足
        log.info("message:{}", message);
        log.info("o:{}", o);
        Order order = JSONArray.parseObject(o.toString(), Order.class);
        // 获取到number
        int number = order.getNumber();
        if (number > 5) {
            log.error("库存不足，回滚");
            return LocalTransactionState.ROLLBACK_MESSAGE;
        } else {
            log.info("消息投递成功");
            return LocalTransactionState.COMMIT_MESSAGE;
        }
    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt messageExt) {
        return null;
    }
}
